home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 5 / Skunkware 5.iso / man / cat.1 / perlref.1 < prev    next >
Text File  |  1995-07-25  |  20KB  |  463 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))  UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 0000....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 00000000))))  PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.           perlref - Perl references and nested data structures
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.           In Perl 4 it was difficult to represent complex data
  13.           structures, because all references had to be symbolic, and
  14.           even that was difficult to do when you wanted to refer to a
  15.           variable rather than a symbol table entry.  Perl 5 not only
  16.           makes it easier to use symbolic references to variables, but
  17.           lets you have "hard" references to any piece of data.  Any
  18.           scalar may hold a hard reference.  Since arrays and hashes
  19.           contain scalars, you can now easily build arrays of arrays,
  20.           arrays of hashes, hashes of arrays, arrays of hashes of
  21.           functions, and so on.
  22.  
  23.           Hard references are smart--they keep track of reference
  24.           counts for you, automatically freeing the thing referred to
  25.           when its reference count goes to zero.  If that thing
  26.           happens to be an object, the object is destructed.  See the
  27.           _p_e_r_l_o_b_j manpage for more about objects.  (In a sense,
  28.           everything in Perl is an object, but we usually reserve the
  29.           word for references to objects that have been officially
  30.           "blessed" into a class package.)
  31.  
  32.           A symbolic reference contains the name of a variable, just
  33.           as a symbolic link in the filesystem merely contains the
  34.           name of a file. The *glob notation is a kind of symbolic
  35.           reference.  Hard references are more like hard links in the
  36.           file system: merely another way at getting at the same
  37.           underlying object, irrespective of its name.
  38.  
  39.           "Hard" references are easy to use in Perl.  There is just
  40.           one overriding principle:  Perl does no implicit referencing
  41.           or dereferencing.  When a scalar is holding a reference, it
  42.           always behaves as a scalar.  It doesn't magically start
  43.           being an array or a hash unless you tell it so explicitly by
  44.           dereferencing it.
  45.  
  46.           References can be constructed several ways.
  47.  
  48.           1.  By using the backslash operator on a variable,
  49.               subroutine, or value.  (This works much like the &
  50.               (address-of) operator works in C.)  Note that this
  51.               typically creates _A_N_O_T_H_E_R reference to a variable, since
  52.               there's already a reference to the variable in the
  53.               symbol table.  But the symbol table reference might go
  54.               away, and you'll still have the reference that the
  55.               backslash returned.  Here are some examples:
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.      Page 1                                          (printed 6/30/95)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))  UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 0000....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 00000000))))  PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  71.  
  72.  
  73.  
  74.                   $scalarref = \$foo;
  75.                   $arrayref  = \@ARGV;
  76.                   $hashref   = \%ENV;
  77.                   $coderef   = \&handler;
  78.  
  79.  
  80.           2.  A reference to an anonymous array can be constructed
  81.               using square brackets:
  82.  
  83.                   $arrayref = [1, 2, ['a', 'b', 'c']];
  84.  
  85.               Here we've constructed a reference to an anonymous array
  86.               of three elements whose final element is itself
  87.               reference to another anonymous array of three elements.
  88.               (The multidimensional syntax described later can be used
  89.               to access this.  For example, after the above,
  90.               $arrayref->[2][1] would have the value "b".)
  91.  
  92.           3.  A reference to an anonymous hash can be constructed
  93.               using curly brackets:
  94.  
  95.                   $hashref = {
  96.                       'Adam'  => 'Eve',
  97.                       'Clyde' => 'Bonnie',
  98.                   };
  99.  
  100.               Anonymous hash and array constructors can be intermixed
  101.               freely to produce as complicated a structure as you
  102.               want.  The multidimensional syntax described below works
  103.               for these too.  The values above are literals, but
  104.               variables and expressions would work just as well,
  105.               because assignment operators in Perl (even within
  106.               _l_o_c_a_l() or _m_y()) are executable statements, not
  107.               compile-time declarations.
  108.  
  109.               Because curly brackets (braces) are used for several
  110.               other things including BLOCKs, you may occasionally have
  111.               to disambiguate braces at the beginning of a statement
  112.               by putting a + or a return in front so that Perl
  113.               realizes the opening brace isn't starting a BLOCK.  The
  114.               economy and mnemonic value of using curlies is deemed
  115.               worth this occasional extra hassle.
  116.  
  117.               For example, if you wanted a function to make a new hash
  118.               and return a reference to it, you have these options:
  119.  
  120.                   sub hashem {        { @_ } }   # silently wrong
  121.                   sub hashem {       +{ @_ } }   # ok
  122.                   sub hashem { return { @_ } }   # ok
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                                          (printed 6/30/95)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))  UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 0000....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 00000000))))  PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  137.  
  138.  
  139.  
  140.           4.  A reference to an anonymous subroutine can be
  141.               constructed by using sub without a subname:
  142.  
  143.                   $coderef = sub { print "Boink!\n" };
  144.  
  145.               Note the presence of the semicolon.  Except for the fact
  146.               that the code inside isn't executed immediately, a sub
  147.               {} is not so much a declaration as it is an operator,
  148.               like do{} or eval{}.  (However, no matter how many times
  149.               you execute that line (unless you're in an eval("...")),
  150.               $coderef will still have a reference to the _S_A_M_E
  151.               anonymous subroutine.)
  152.  
  153.               For those who worry about these things, the current
  154.               implementation uses shallow binding of _l_o_c_a_l()
  155.               variables; _m_y() variables are not accessible.  This
  156.               precludes true closures.  However, you can work around
  157.               this with a run-time (rather than a compile-time)
  158.               _e_v_a_l():
  159.  
  160.                   {
  161.                       my $x = time;
  162.                       $coderef = eval "sub { \$x }";
  163.                   }
  164.  
  165.               Normally--if you'd used just sub{} or even eval{}--your
  166.               unew sub would only have been able to access the global
  167.               $x.  But because you've used a run-time _e_v_a_l(), this
  168.               will not only generate a brand new subroutine reference
  169.               each time called, it will all grant access to the _m_y()
  170.               variable lexically above it rather than the global one.
  171.               The particular $x accessed will be different for each
  172.               new sub you create.  This mechanism yields deep binding
  173.               of variables.  (If you don't know what closures, deep
  174.               binding, or shallow binding are, don't worry too much
  175.               about it.)
  176.  
  177.           5.  References are often returned by special subroutines
  178.               called constructors.  Perl objects are just reference a
  179.               special kind of object that happens to know which
  180.               package it's associated with.  Constructors are just
  181.               special subroutines that know how to create that
  182.               association.  They do so by starting with an ordinary
  183.               reference, and it remains an ordinary reference even
  184.               while it's also being an object.  Constructors are
  185.               customarily named _n_e_w(), but don't have to be:
  186.  
  187.                   $objref = new Doggie (Tail => 'short', Ears => 'long');
  188.  
  189.  
  190.           6.  References of the appropriate type can spring into
  191.               existence if you dereference them in a context that
  192.  
  193.  
  194.  
  195.      Page 3                                          (printed 6/30/95)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))  UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 0000....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 00000000))))  PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  203.  
  204.  
  205.  
  206.               assumes they exist.  Since we haven't talked about
  207.               dereferencing yet, we can't show you any examples yet.
  208.  
  209.           That's it for creating references.  By now you're probably
  210.           dying to know how to use references to get back to your
  211.           long-lost data.  There are several basic methods.
  212.  
  213.           1.  Anywhere you'd put an identifier as part of a variable
  214.               or subroutine name, you can replace the identifier with
  215.               a simple scalar variable containing a reference of the
  216.               correct type:
  217.  
  218.                   $bar = $$scalarref;
  219.                   push(@$arrayref, $filename);
  220.                   $$arrayref[0] = "January";
  221.                   $$hashref{"KEY"} = "VALUE";
  222.                   &$coderef(1,2,3);
  223.  
  224.               It's important to understand that we are specifically
  225.               _N_O_T dereferencing $arrayref[0] or $hashref{"KEY"} there.
  226.               The dereference of the scalar variable happens _B_E_F_O_R_E it
  227.               does any key lookups.  Anything more complicated than a
  228.               simple scalar variable must use methods 2 or 3 below.
  229.               However, a "simple scalar" includes an identifier that
  230.               itself uses method 1 recursively.  Therefore, the
  231.               following prints "howdy".
  232.  
  233.                   $refrefref = \\\"howdy";
  234.                   print $$$$refrefref;
  235.  
  236.  
  237.           2.  Anywhere you'd put an identifier as part of a variable
  238.               or subroutine name, you can replace the identifier with
  239.               a BLOCK returning a reference of the correct type.  In
  240.               other words, the previous examples could be written like
  241.               this:
  242.  
  243.                   $bar = ${$scalarref};
  244.                   push(@{$arrayref}, $filename);
  245.                   ${$arrayref}[0] = "January";
  246.                   ${$hashref}{"KEY"} = "VALUE";
  247.                   &{$coderef}(1,2,3);
  248.  
  249.               Admittedly, it's a little silly to use the curlies in
  250.               this case, but the BLOCK can contain any arbitrary
  251.               expression, in particular, subscripted expressions:
  252.  
  253.                   &{ $dispatch{$index} }(1,2,3);      # call correct routine
  254.  
  255.               Because of being able to omit the curlies for the simple
  256.               case of $$x, people often make the mistake of viewing
  257.               the dereferencing symbols as proper operators, and
  258.  
  259.  
  260.  
  261.      Page 4                                          (printed 6/30/95)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))  UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 0000....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 00000000))))  PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  269.  
  270.  
  271.  
  272.               wonder about their precedence.  If they were, though,
  273.               you could use parens instead of braces.  That's not the
  274.               case.  Consider the difference below; case 0 is a
  275.               short-hand version of case 1, _N_O_T case 2:
  276.  
  277.                   $$hashref{"KEY"}   = "VALUE";       # CASE 0
  278.                   ${$hashref}{"KEY"} = "VALUE";       # CASE 1
  279.                   ${$hashref{"KEY"}} = "VALUE";       # CASE 2
  280.                   ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
  281.  
  282.               Case 2 is also deceptive in that you're accessing a
  283.               variable called %hashref, not dereferencing through
  284.               $hashref to the hash it's presumably referencing.  That
  285.               would be case 3.
  286.  
  287.           3.  The case of individual array elements arises often
  288.               enough that it gets cumbersome to use method 2.  As a
  289.               form of syntactic sugar, the two lines like that above
  290.               can be written:
  291.  
  292.                   $arrayref->[0] = "January";
  293.                   $hashref->{"KEY} = "VALUE";
  294.  
  295.               The left side of the array can be any expression
  296.               returning a reference, including a previous dereference.
  297.               Note that $array[$x] is _N_O_T the same thing as $array-
  298.               >[$x] here:
  299.  
  300.                   $array[$x]->{"foo"}->[0] = "January";
  301.  
  302.               This is one of the cases we mentioned earlier in which
  303.               references could spring into existence when in an lvalue
  304.               context.  Before this statement, $array[$x] may have
  305.               been undefined.  If so, it's automatically defined with
  306.               a hash reference so that we can look up {"foo"} in it.
  307.               Likewise $array[$x]->{"foo"} will automatically get
  308.               defined with an array reference so that we can look up
  309.               [0] in it.
  310.  
  311.               One more thing here.  The arrow is optional _B_E_T_W_E_E_N
  312.               brackets subscripts, so you can shrink the above down to
  313.  
  314.                   $array[$x]{"foo"}[0] = "January";
  315.  
  316.               Which, in the degenerate case of using only ordinary
  317.               arrays, gives you multidimensional arrays just like C's:
  318.  
  319.                   $score[$x][$y][$z] += 42;
  320.  
  321.               Well, okay, not entirely like C's arrays, actually.  C
  322.               doesn't know how to grow its arrays on demand.  Perl
  323.               does.
  324.  
  325.  
  326.  
  327.      Page 5                                          (printed 6/30/95)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))  UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 0000....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 00000000))))  PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  335.  
  336.  
  337.  
  338.           4.  If a reference happens to be a reference to an object,
  339.               then there are probably methods to access the things
  340.               referred to, and you should probably stick to those
  341.               methods unless you're in the class package that defines
  342.               the object's methods.  In other words, be nice, and
  343.               don't violate the object's encapsulation without a very
  344.               good reason.  Perl does not enforce encapsulation.  We
  345.               are not totalitarians here.  We do expect some basic
  346.               civility though.
  347.  
  348.           The _r_e_f() operator may be used to determine what type of
  349.           thing the reference is pointing to.  See the _p_e_r_l_f_u_n_c
  350.           manpage.
  351.  
  352.           The _b_l_e_s_s() operator may be used to associate a reference
  353.           with a package functioning as an object class.  See the
  354.           _p_e_r_l_o_b_j manpage.
  355.  
  356.           A type glob may be dereferenced the same way a reference
  357.           can, since the dereference syntax always indicates the kind
  358.           of reference desired.  So ${*foo} and ${\$foo} both indicate
  359.           the same scalar variable.
  360.  
  361.           Here's a trick for interpolating a subroutine call into a
  362.           string:
  363.  
  364.               print "My sub returned ${\mysub(1,2,3)}\n";
  365.  
  366.           The way it works is that when the ${...} is seen in the
  367.           double-quoted string, it's evaluated as a block.  The block
  368.           executes the call to mysub(1,2,3), and then takes a
  369.           reference to that.  So the whole block returns a reference
  370.           to a scalar, which is then dereferenced by ${...} and stuck
  371.           into the double-quoted string.
  372.  
  373.           SSSSyyyymmmmbbbboooolllliiiicccc rrrreeeeffffeeeerrrreeeennnncccceeeessss
  374.  
  375.           We said that references spring into existence as necessary
  376.           if they are undefined, but we didn't say what happens if a
  377.           value used as a reference is already defined, but _I_S_N'_T a
  378.           hard reference.  If you use it as a reference in this case,
  379.           it'll be treated as a symbolic reference.  That is, the
  380.           value of the scalar is taken to be the _N_A_M_E of a variable,
  381.           rather than a direct link to a (possibly) anonymous value.
  382.  
  383.           People frequently expect it to work like this.  So it does.
  384.  
  385.  
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                                          (printed 6/30/95)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))  UUUUNNNNIIIIXXXX SSSSyyyysssstttteeeemmmm VVVV ((((RRRReeeelllleeeeaaaasssseeee 0000....0000 PPPPaaaattttcccchhhhlllleeeevvvveeeellll 00000000))))  PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  401.  
  402.  
  403.  
  404.               $name = "foo";
  405.               $$name = 1;                 # Sets $foo
  406.               ${$name} = 2;               # Sets $foo
  407.               ${$name x 2} = 3;           # Sets $foofoo
  408.               $name->[0] = 4;             # Sets $foo[0]
  409.               @$name = ();                # Clears @foo
  410.               &$name();                   # Calls &foo() (as in Perl 4)
  411.               $pack = "THAT";
  412.               ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
  413.  
  414.           This is very powerful, and slightly dangerous, in that it's
  415.           possible to intend (with the utmost sincerity) to use a hard
  416.           reference, and accidentally use a symbolic reference
  417.           instead.  To protect against that, you can say
  418.  
  419.               use strict 'refs';
  420.  
  421.           and then only hard references will be allowed for the rest
  422.           of the enclosing block.  An inner block may countermand that
  423.           with
  424.  
  425.               no strict 'refs';
  426.  
  427.           Only package variables are visible to symbolic references.
  428.           Lexical variables (declared with _m_y()) aren't in a symbol
  429.           table, and thus are invisible to this mechanism.  For
  430.           example:
  431.  
  432.               local($value) = 10;
  433.               $ref = \$value;
  434.               {
  435.                   my $value = 20;
  436.                   print $$ref;
  437.               }
  438.  
  439.           This will still print 10, not 20.  Remember that _l_o_c_a_l()
  440.           affects package variables, which are all "global" to the
  441.           package.
  442.  
  443.           FFFFuuuurrrrtttthhhheeeerrrr RRRReeeeaaaaddddiiiinnnngggg
  444.  
  445.           Besides the obvious documents, source code can be
  446.           instructive.  Some rather pathological examples of the use
  447.           of references can be found in the _t/_o_p/_r_e_f._t regression test
  448.           in the Perl source directory.
  449.  
  450.  
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                                          (printed 6/30/95)
  460.  
  461.  
  462.  
  463.